<?php

namespace App\Exceptions;

use App\Http\Traits\ApiResponse;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Validation\ValidationException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    use ApiResponse;

    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Throwable  $exception
     * @return void
     *
     * @throws \Exception
     */
    public function report(Throwable $exception)
    {
        $context = [
            'file' => $exception->getFile(),
            'line' => $exception->getLine()
        ];
        if (config('app.debug')) {
            $context['trace'] = $exception->getTraceAsString();
        }

        try {
            $logger = app(LoggerInterface::class);
        } catch (\Exception $exception) {
            throw $exception; // throw the original exception
        }
        $logger->error($exception->getMessage(), $context);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $exception
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     *
     * @throws \Throwable
     */
    public function render($request, Throwable $exception)
    {
        // 参数验证异常
        if ($exception instanceof ValidationException) {
            return $this->setHttpCode(200)->failed($exception->validator->errors()->first());
        }

        // http错误，返回404错误
        if ($exception instanceof HttpException) {
            $status = $exception->getStatusCode();
            $message = $exception->getMessage() ?: 'Router不存在，请检查请求URL';
            return $this->setHttpCode(200)->failed($message, $status);
        }

        // 基础错误
        if ($exception instanceof \Exception) {
            return $this->setHttpCode(200)->failed($exception->getMessage(), 500);
        }

        // 服务错误，返回500错误
        if ($exception instanceof \ParseError) {
            return $this->setHttpCode(200)->failed($exception->getMessage(), 501);
        }

        //自定义
        if ($exception instanceof \Error) {
            return $this->setHttpCode(200)->failed($exception->getMessage(), 502);
        }

        return parent::render($request, $exception);
    }
}
